package com.mq.listener.e_dlx;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class DeadLetterListener {

    /**
     * 消息确认、消费者可靠性保证
     */
    @RabbitListener(queues = "normal.queue")
    public void handle(String content, Channel channel, Message message) throws IOException {
        try {
            String str = null;
            str.length();
            System.out.println("消费者收到 normal.queue 消息：" + content);
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //throw new RuntimeException(e);

            // 1、获取重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            // 2、判断1：如果没有重投过，就重投
            if (!redelivered) {
                // 重投
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
            else {
                // 3、判断2：如果重投过，就拒绝
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }

        }
    }
}